import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemUserApi } from '#/api/system/user';

import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { $t } from '@vben/locales';
import { handleTree } from '@vben/utils';

import { z } from '#/adapter/form';
import { getDeptListCondition } from '#/api/system/dept';
import { getSimplePostListQuery } from '#/api/system/post';
import { getSimpleRoleList } from '#/api/system/role';
import { getRangePickerDefaultProps } from '#/utils';

/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'id',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'username',
      label: '用户名称',
      component: 'Input',
      rules: 'required',
    },
    {
      fieldName: 'nickname',
      label: '用户昵称',
      component: 'Input',
      rules: 'required',
    },
    {
      label: '用户密码',
      fieldName: 'password',
      component: 'InputPassword',
      rules: 'required',
      dependencies: {
        triggerFields: ['id'],
        show: (values) => !values.id,
      },
    },
    {
      fieldName: 'fullName',
      label: '姓名',
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'cardType',
      label: '证件类型',
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.SYSTEM_CARD_TYPE, 'string'),
        buttonStyle: 'solid',
        optionType: 'button',
      },
    },
    {
      fieldName: 'idcard',
      label: '证件号码',
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'areaCode',
      label: '行政区划',
      component: 'ApiTreeSelect',
      componentProps(values) {
        return {
          api: async () => {
            const data = await getDeptListCondition({ type: 'area' });
            return handleTree(data);
          },
          labelField: 'name',
          valueField: 'id',
          childrenField: 'children',
          placeholder: '请选择行政区划',
          treeDefaultExpandAll: true,
          allowClear: true,
          onChange: (val) => {
            // 清空值，避免残留
            values.unitId = undefined;
            values.deptId = undefined;
            values.postIds = undefined;
          },
        };
      },
    },
    {
      fieldName: 'unitId',
      label: '单位',
      component: 'ApiTreeSelect',
      dependencies: {
        triggerFields: ['areaCode'],
        componentProps: (values) => {
          return {
            // 关键：用 areaCode 作为 key，强制重新渲染
            key: values.areaCode || 'all',
            api: async () => {
              const data = await getDeptListCondition({
                type: 'unit',
                ...(values.areaCode ? { areaCode: values.areaCode } : {}),
              });
              return handleTree(data);
            },
            labelField: 'name',
            valueField: 'id',
            childrenField: 'children',
            placeholder: '请选择单位',
            treeDefaultExpandAll: false,
            treeLine: true,
            allowClear: true,
            onChange: (val) => {
              // 清空值，避免残留
              values.deptId = undefined;
              values.postIds = undefined;
            },
          };
        },
      },
    },
    {
      fieldName: 'deptId',
      label: '归属部门',
      component: 'ApiTreeSelect',
      dependencies: {
        triggerFields: ['unitId'],
        componentProps: (values) => {
          return {
            // 关键：用 unitId 作为 key，强制重新渲染
            key: values.unitId || 'all',
            api: async () => {
              const data = await getDeptListCondition({
                type: 'dept',
                ...(values.unitId ? { unitId: values.unitId } : {}),
              });
              return handleTree(data);
            },
            labelField: 'name',
            valueField: 'id',
            childrenField: 'children',
            placeholder: '请选择归属部门',
            treeDefaultExpandAll: false,
            allowClear: true,
          };
        },
      },
    },
    {
      fieldName: 'postIds',
      label: '岗位',
      component: 'Select',
      dependencies: {
        triggerFields: ['unitId', 'deptId'],
        componentProps: async (values) => {
          let res: any[] = [];
          // 先根据 deptId 查询，如果有数据就返回
          if (values.deptId) {
            res = await getSimplePostListQuery({
              deptId: values.deptId,
            });
          }
          // 如果 deptId 没有或者查不到，再根据 unitId 查询
          if ((!values.deptId || res.length === 0) && values.unitId) {
            res = await getSimplePostListQuery({
              deptId: values.unitId,
            });
          }

          const options = res
            ? res.map((item) => ({
                value: item.id,
                label: item.name,
              }))
            : [];

          return {
            // 关键：用 postIds 作为 key，强制重新渲染
            key: values.postIds || 'all',
            options,
            mode: 'multiple',
            placeholder: '请选择岗位',
            allowClear: true,
          };
        },
      },
    },
    {
      fieldName: 'email',
      label: '邮箱',
      component: 'Input',
      rules: z.string().email('邮箱格式不正确').or(z.literal('')).optional(),
    },
    {
      fieldName: 'mobile',
      label: '手机号码',
      component: 'Input',
    },
    {
      fieldName: 'sex',
      label: '用户性别',
      component: 'RadioGroup',
      componentProps: {
        options: getDictOptions(DICT_TYPE.SYSTEM_USER_SEX, 'number'),
        buttonStyle: 'solid',
        optionType: 'button',
      },
      rules: z.number().default(1),
    },
    {
      fieldName: 'status',
      label: '用户状态',
      component: 'RadioGroup',
      componentProps: {
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
        buttonStyle: 'solid',
        optionType: 'button',
      },
      rules: z.number().default(CommonStatusEnum.ENABLE),
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'Textarea',
      formItemClass: 'col-span-2',
    },
  ];
}

/** 重置密码的表单 */
export function useResetPasswordFormSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'id',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        passwordStrength: true,
        placeholder: '请输入新密码',
      },
      dependencies: {
        rules(values) {
          return z
            .string({ message: '请输入新密码' })
            .min(5, '密码长度不能少于 5 个字符')
            .max(20, '密码长度不能超过 20 个字符')
            .refine(
              (value) => value !== values.oldPassword,
              '新旧密码不能相同',
            );
        },
        triggerFields: ['newPassword', 'oldPassword'],
      },
      fieldName: 'newPassword',
      label: '新密码',
      rules: 'required',
    },
    {
      fieldName: 'confirmPassword',
      label: '确认密码',
      component: 'VbenInputPassword',
      componentProps: {
        passwordStrength: true,
        placeholder: $t('authentication.confirmPassword'),
      },
      dependencies: {
        rules(values) {
          return z
            .string({ message: '请输入确认密码' })
            .min(5, '密码长度不能少于 5 个字符')
            .max(20, '密码长度不能超过 20 个字符')
            .refine(
              (value) => value === values.newPassword,
              '新密码和确认密码不一致',
            );
        },
        triggerFields: ['newPassword', 'confirmPassword'],
      },
    },
  ];
}

/** 分配角色的表单 */
export function useAssignRoleFormSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'id',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'username',
      label: '用户名称',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      fieldName: 'nickname',
      label: '用户昵称',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      fieldName: 'roleIds',
      label: '角色',
      component: 'ApiSelect',
      componentProps: {
        api: getSimpleRoleList,
        labelField: 'name',
        valueField: 'id',
        mode: 'multiple',
        placeholder: '请选择角色',
      },
    },
  ];
}

/** 分配组织的表单 */
export function useAssignOrgFormSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'id',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      component: 'Input',
      fieldName: 'deptId',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'username',
      label: '用户名称',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      fieldName: 'nickname',
      label: '用户昵称',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      fieldName: 'orgIds',
      label: '组织',
      component: 'ApiTreeSelect',
      componentProps: (value) => {
        return {
          // 异步获取组织树数据
          api: async () => {
            const data = await getDeptListCondition({}); // 调用接口获取部门/组织数据
            const treeData = handleTree(data); // 转换成树形结构

            const currentOrgId = value.deptId; // 获取当前用户所属的组织ID（

            // 递归遍历树，禁用当前用户的组织节点
            const disableCurrentOrg = (nodes) => {
              return nodes.map((node) => {
                // 如果节点ID是当前组织ID，则禁用该节点
                if (node.id === currentOrgId) {
                  node.disabled = true;
                }
                // 如果有子节点，递归处理
                if (node.children && node.children.length > 0) {
                  node.children = disableCurrentOrg(node.children);
                }
                return node;
              });
            };

            return disableCurrentOrg(treeData); // 返回处理后的树数据
          },
          labelField: 'name',
          valueField: 'id',
          childrenField: 'children',
          multiple: true, // 允许多选
          placeholder: '请选择组织',
          defaultValue: value.deptId ? [value.deptId] : [], // 默认选中当前组织（如果有值）
        };
      },
    },

    // {
    //   fieldName: 'orgIds',
    //   label: '组织',
    //   component: 'ApiTreeSelect',
    //   componentProps: {
    //     api: async () => {
    //       const data = await getDeptListCondition({});
    //       return handleTree(data);
    //     },
    //     labelField: 'name',
    //     valueField: 'id',
    //     childrenField: 'children',
    //     multiple: true,
    //     placeholder: '请选择组织',
    //   },
    // },
  ];
}

/** 用户导入的表单 */
export function useImportFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'file',
      label: '用户数据',
      component: 'Upload',
      rules: 'required',
      help: '仅允许导入 xls、xlsx 格式文件',
    },
    {
      fieldName: 'updateSupport',
      label: '是否覆盖',
      component: 'Switch',
      componentProps: {
        checkedChildren: '是',
        unCheckedChildren: '否',
      },
      rules: z.boolean().default(false),
      help: '是否更新已经存在的用户数据',
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'username',
      label: '用户名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入用户名称',
        allowClear: true,
      },
    },
    {
      fieldName: 'mobile',
      label: '手机号码',
      component: 'Input',
      componentProps: {
        placeholder: '请输入手机号码',
        allowClear: true,
      },
    },
    {
      fieldName: 'fullName',
      label: '真实名字',
      component: 'Input',
      componentProps: {
        placeholder: '请输入真实名字',
      },
    },
    {
      fieldName: 'idcard',
      label: '证件号码',
      component: 'Input',
      componentProps: {
        placeholder: '请输入证件号码',
      },
    },
    {
      fieldName: 'createTime',
      label: '创建时间',
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns<T = SystemUserApi.User>(
  onStatusChange?: (
    newStatus: number,
    row: T,
  ) => PromiseLike<boolean | undefined>,
): VxeTableGridOptions['columns'] {
  return [
    { type: 'checkbox', width: 40 },
    {
      field: 'id',
      title: '用户编号',
      minWidth: 100,
      visible: false,
    },
    {
      field: 'username',
      title: '用户名称',
      minWidth: 150,
    },
    {
      field: 'nickname',
      title: '用户昵称',
      minWidth: 150,
    },
    {
      field: 'fullName',
      title: '姓名',
      minWidth: 120,
    },
    {
      field: 'idcard',
      title: '证件号码',
      minWidth: 120,
    },
    {
      field: 'deptName',
      title: '部门',
      minWidth: 180,
    },
    {
      field: 'mobile',
      title: '手机号码',
      minWidth: 100,
    },
    {
      field: 'status',
      title: '状态',
      align: 'center',
      minWidth: 100,
      cellRender: {
        attrs: { beforeChange: onStatusChange },
        name: 'CellSwitch',
        props: {
          checkedValue: CommonStatusEnum.ENABLE,
          unCheckedValue: CommonStatusEnum.DISABLE,
        },
      },
    },
    {
      field: 'createTime',
      title: '创建时间',
      minWidth: 180,
      formatter: 'formatDateTime',
    },
    {
      field: 'actions',
      title: '操作',
      width: 180,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}
